//
//  ViewController.m
//  LayerProperty
//
//  Created by hao on 2018/3/16.
//  Copyright © 2018年 hao. All rights reserved.
//

#import "ViewController.h"
#import "Header.h"

@interface ViewController () <CALayerDelegate>

@property (nonatomic, weak) UIView *layerView;

@property (nonatomic, weak) UIView *originalView;

@property (nonatomic, weak) CALayer *greenLayer;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.view.backgroundColor = UIColorWithRGB(160, 160, 160);
//    [self layerContentProperty];
//    [self layerCoordinateLayout];
//    [self layerCornerBorderShadow];
//    [self layerMaskStretchFilter];
    [self layerGroupOpacity];
}

/** 图层的组透明， */
- (void)layerGroupOpacity
{
    self.view.backgroundColor = RandomColor;
    //create opaque button
    UIButton *button1 = [self customButton];
    button1.center = CGPointMake(80, 150);
    [self.view addSubview:button1];
    
    //create translucent button
    UIButton *button2 = [self customButton];
    
    button2.center = CGPointMake(240, 150);
    button2.alpha = 0.5;
    [self.view addSubview:button2];
    
    //enable rasterization for the translucent button
    // 目前iOS11，Xcode9.2的版本无论设不设置都会实现组透明，即父视图设置透明度后子试图也会一致
//    button2.layer.shouldRasterize = YES;
//    button2.layer.rasterizationScale = [UIScreen mainScreen].scale;
}

/** 图层 蒙板拉伸过滤 */
- (void)layerMaskStretchFilter
{
    UIImage *image = [UIImage imageNamed:@"icon"];
    self.layerView.layer.contents = (__bridge id)image.CGImage;
    
    CALayer *maskLayer = [CALayer layer];
    maskLayer.frame = self.layerView.bounds;
    maskLayer.contents = (__bridge id)[UIImage imageNamed:@"guzhangma_4"].CGImage;
    [self.layerView.layer addSublayer:maskLayer];
    // mask相当于 把maskLayer透明部分全部隐藏，只显示实心部分, 有点像投影
    // 在self.layerView.layer图层上显示maskLayer实心部分的形状，内容还是layerView.layer
//    self.layerView.layer.mask = maskLayer;
    
    self.layerView.layer.minificationFilter = kCAFilterNearest;
    self.layerView.layer.minificationFilterBias = 0.5;
}

/** 图层的视觉效果，圆角边框阴影 */
- (void)layerCornerBorderShadow
{
    CALayer *orgLayer = [CALayer layer];
    orgLayer.backgroundColor = [UIColor orangeColor].CGColor;
    orgLayer.frame = CGRectMake(-50, -50, 100, 100);
    [self.layerView.layer addSublayer:orgLayer];
    self.layerView.frame = CGRectMake(100, 100, 130, 100);
//    self.originalView.frame = CGRectMake(50, 50, 100, 100);
    
    self.layerView.backgroundColor = [UIColor clearColor];
    self.layerView.layer.cornerRadius = 10;
    self.layerView.layer.borderWidth = 2.f;
    self.layerView.layer.borderColor = [UIColor clearColor].CGColor;
    // 设置masksToBounds = YES后阴影也会裁剪掉
//    self.layerView.layer.masksToBounds = YES;
    // 阴影半径
//    self.layerView.layer.shadowRadius = 5;
    // 阴影颜色
    self.layerView.layer.shadowColor = RandomColor.CGColor;
    // 设置阴影透明
    self.layerView.layer.shadowOpacity = .5f;
    // 设置阴影偏移方向,系统默认(0, -3)向上
//    self.layerView.layer.shadowOffset = CGSizeMake(0, 3);
    
    CGMutablePathRef path = CGPathCreateMutable();
//    CGPathAddRect(path, NULL, self.layerView.bounds);
    // 创建一个椭圆的路径
    CGPathAddEllipseInRect(path, NULL, self.layerView.bounds);
    self.layerView.layer.shadowPath = path;
    CGPathRelease(path);
}

/** 坐标布局，锚点 */
- (void)layerCoordinateLayout
{
    self.originalView.backgroundColor = [UIColor orangeColor];
    self.originalView.frame = CGRectMake(10, 20, 50, 50);
    // zPosition属性可以改变图层的顺序，增加一个像素就可以前置, 但不能改变事件传递的顺序。
    self.originalView.layer.zPosition = 1.0f;
    
    self.layerView.layer.backgroundColor = [UIColor blueColor].CGColor;
    self.layerView.frame = CGRectMake(20, 100, 100, 100);
    
    CALayer *grl = [CALayer layer];
    grl.frame = CGRectMake(20.0f, 20.0f, 50.0f, 50.0f);
    grl.backgroundColor = [UIColor greenColor].CGColor;
    [self.layerView.layer addSublayer:grl];
    self.greenLayer = grl;
    // 旋转之后frame的宽高也会改变，但是bounds的宽高不变还是初始化时的宽高
//    self.layerView.transform = CGAffineTransformRotate(CGAffineTransformIdentity, M_PI_4);
    // 就是把坐标范围比例为0-1， 将设置的点移动到中点， 比如(0, 1)即左下角移动到原中点
//    self.layerView.layer.anchorPoint = CGPointMake(0.5, 0);
    // layer.position 相当于 view.center
//    NSLogPoint(self.layerView.layer.position);
//    NSLogPoint(self.layerView.center);
}

/** 测试layer的contents属性 */
- (void)layerContentProperty
{
    // 为什么layer的被定义为id类型，因为Core Animation是iOS和macOS共用的，在macOS中contents属性对CGImage和NSImage两种类型的值都起作用，如果试图在iOS平台使用UIImage类型赋值，只能得到空白图层。
    // 最终赋值给contents的是CGImageRef，指向CGImage结构的指针。UIImage.CGImage会返回一个CGImageRef，但是不能直接赋值给layer.contents，编译器报错: Implicit conversion of C pointer type 'CGImageRef _Nullable' (aka 'struct CGImage *') to Objective-C pointer type 'id _Nullable' requires a bridged cast 因为该CGImageRef是Core Funndation中的类型，Cocoa要使用bridge关键字转化 -> (__bridge id)image.CGImage
    UIImage *image = [UIImage imageNamed:@"icon"];
//    self.layerView.layer.contents = (__bridge id)image.CGImage;
    // 与layerView的效果做对比
    self.originalView.layer.contents = (__bridge id)image.CGImage;
    
    // contentsGravity 等价于 view.contentMode, 决定内容在图层的边界中怎么对齐
//    self.layerView.layer.contentsGravity = kCAGravityCenter;
    
    // 如果单纯放大图层的 contents 图片，使用 transform 和 affineTransform
    // contentsScale支持高分辨率屏幕(Hi-DPI或Retina)机制,如果设置为1.0，就以1个像素点绘制图片，值为2.0就两个像素点绘制
//    self.layerView.layer.contentsScale = image.scale;
    
    // 可以使用该属性做图片拼合(四张图片重叠，各取四分之一)，contentsRect位置是相对的
    // 当CGRectMake(0, 0, 0.5, 0.5)时，表示只显示左上角的那部分，起点是(0, 0),终点是原始宽高的一半
//    self.layerView.layer.contentsRect = CGRectMake(0, 0, 0.5, 0.5);
    
    // 与UIImage的 -resizableImageWithCapInsets: 方法效果非常类似. 在Interface Builder里可以配置Stretching
//    self.layerView.layer.contentsCenter = CGRectMake(0.25, 0.25, 0.5, 0.5);
    
    // 添加一个layer并设置self为代理
    CALayer *delegateLayer = [[CALayer alloc] init];
    delegateLayer.frame = CGRectMake(10.0f, 10.0f, 20.0f, 20.0f);
    delegateLayer.backgroundColor = [UIColor blueColor].CGColor;
    delegateLayer.delegate = self;
    [self.layerView.layer addSublayer:delegateLayer];
}

#pragma mark - CALayerDelegate
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx
{
    CGContextSetLineWidth(ctx, 10);
    CGContextSetStrokeColorWithColor(ctx, [UIColor greenColor].CGColor);
    CGContextFillEllipseInRect(ctx, layer.bounds);
}

- (UIView *)layerView
{
    if (!_layerView) {
        UIView *v = [[UIView alloc] init];
        v.backgroundColor = [UIColor blueColor];
        [self.view addSubview:v];
        v.frame = CGRectMake(0, 0, 84, 84);
        v.center = CGPointMake(ScreenWidth*0.5, ScreenHeight*0.5);
        _layerView = v;
    }
    return _layerView;
}

- (UIView *)originalView
{
    if (!_originalView) {
        UIView *v = [[UIView alloc] init];
        v.backgroundColor = [UIColor orangeColor];
        [self.view addSubview:v];
        v.frame = CGRectMake(60, 60, 84, 84);
        _originalView = v;
    }
    return _originalView;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self testLayerHitTest:touches];
}

/** 测试layer的点击捕捉 */
- (void)testLayerHitTest:(NSSet<UITouch *> *)touches
{
    // 获取点击的坐标
    CGPoint hitPoint = [[touches anyObject] locationInView:self.view];
    NSLogPoint(hitPoint);
    
    // 第一种: 使用 hitTest方法
    // 该方法返回一个layer，判断是不是同一个layer，是表示点击该layer上, 超过self.layerView.layer范围的返回nil
    CALayer *hitLayer = [self.layerView.layer hitTest:hitPoint];
    if (hitLayer == self.greenLayer) {
        NSLogObj(@"Inside Green Layer");
    } else if (self.layerView.layer == hitLayer) {
        NSLogObj(@"Inside Layer View");
    }
    
    return ;
    // 第二种: 点转换，判断点在不在layer中
    // 坐标转换, 将hitPoint在self.view.layer的坐标转化成self.layerView.layer中的坐标
    hitPoint = [self.layerView.layer convertPoint:hitPoint fromLayer:self.view.layer];
    NSLogPoint(hitPoint);
    if ([self.layerView.layer containsPoint:hitPoint]) {
        hitPoint = [self.greenLayer convertPoint:hitPoint fromLayer:self.layerView.layer];
        NSLogPoint(hitPoint);
        if ([self.greenLayer containsPoint:hitPoint]) {
            NSLogObj(@"Inside Green Layer");
        } else {
            NSLogObj(@"Inside Layer View");
        }
    }
}

- (UIButton *)customButton
{
    //create button
    CGRect frame = CGRectMake(0, 0, 150, 50);
    UIButton *button = [[UIButton alloc] initWithFrame:frame];
    button.backgroundColor = [UIColor whiteColor];
    button.layer.cornerRadius = 10;
    
    //add label
    frame = CGRectMake(20, 10, 110, 30);
    UILabel *label = [[UILabel alloc] initWithFrame:frame];
    label.text = @"Hello World";
    label.backgroundColor = [UIColor orangeColor];
    label.textAlignment = NSTextAlignmentCenter;
    [button addSubview:label];
    return button;
}

@end


